package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"novel/models"
)

type Novel struct {
	beego.Controller
}
type Res struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *Novel) Add() {

	title := c.GetString("title")
	author := c.GetString("author")
	img := c.GetString("img")
	if title == "" || author == "" || img == "" {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "参数不能为空",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	novel := models.Novel{
		Title:  title,
		Author: author,
		Img:    img,
	}
	err := models.DB.Create(&novel).Error
	file, header, err := c.GetFile("img")
	defer file.Close()
	path := "static/img/" + header.Filename
	err = c.SaveToFile("img", path)
	if header.Size > 2*1024*1024 {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "图片参数过大无法上传",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "上传失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "上传成功",
			Data: "127.0.0.1:8080" + path,
		}
		c.ServeJSON()
		return
	}
}
func (c *Novel) List() {
	var novel []models.Novel
	var err error
	err = models.DB.Find(&novel).Error
	//key := "novel_list"
	//res, _ := cache.Rdb.Get(cache.Ctx, key).Result()
	//if res != "" {
	//	jsonData, _ := json.Marshal(novel)
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "展示失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		//cache.Rdb.Set(cache.Ctx, key, jsonData, 0)
		//json.Unmarshal([]byte(res), &novel)
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "展示成功",
			Data: novel,
		}
		c.ServeJSON()

	}
}

// }
func (c *Novel) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Where("id=?", id).Delete(&models.Novel{}, id).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
}
func (c *Novel) Show() {
	id, _ := c.GetInt("id")
	var novel []models.Novel
	err := models.DB.Where("id=?", id).First(&novel).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "查询成功",
			Data: novel,
		}
		c.ServeJSON()
		return
	}
}
